﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using hedefgrup.reports.renault.implementation;
using hedefgrup.reports.renault;
using hedefgrup.reports.renault.date;
using hedefgrup.reports.renault.definitions;
using hedefgrup.reports.renault.calculators;
using System.Collections.Generic;
using System.Globalization;

public partial class analysisResults : reportPage
{
    private const string REPORT_SUMMARY_ROW_TEMPLATE = "<tr><td width='19%' class=t_head2 bgcolor='#F3F3F3'>&nbsp;{0}</td><td width='29%' class=t_head2 bgcolor='#FFFFFF'>&nbsp;{1}</td><td width='29%' class=t_head2 bgcolor='#F3F3F3'>&nbsp;{2}</td><td width='19%' class=t_head2 bgcolor='#FFFFFF'>&nbsp;{3}</td></tr>";
    private const string REPORT_HEADER_CELL_TEMPLATE = "<td width=100 class=t_head align=center style=''>{0}</td>";
    private const string REPORT_SEPERATOR_ROW_TEMPLATE = "<tr><td width=60 class=t_head style='height:25px;background-color: #336699; color:#FFFFFF' >&nbsp; {0}</td><td width=400 class=t_head style='background-color: #336699; color:#FFFFFF'>&nbsp;{1}</td><td width=80 class=t_head style='background-color: #336699; color:#FFFFFF'>&nbsp;</td><td width=40 class=t_head colspan={2} style='background-color: #336699;'>&nbsp;</td></tr>";
    private const string QUESTION_CELL = "<td width=80 class='vktxt8' style='background-color:#DADADA'></td>";
    private const string REPORT_CELL_DATA_TEMPLATE = "<td width=80 class='vktxt8' style='{1};text-align:right;'>{0:0.0}</td>";
    private const string VERBATIM_CELL_DATA_TEMPLATE = "<td width=80 class='vktxt8' style='{1};text-align:right;'><a href=\"/forms/common/verbatimView.aspx?m={0}&c={1}&d={2}&QUESTION={3}&VARYBYCOLUMN={5}\">{4}</a></td>";
    private const string FAILURE_CELL_STYLE = "background-color:#800000;color:white;";
    private const string SUCCESS_CELL_STYLE = "background-color:#008000;color:white;";
    private const string IMPORTANT_CELL_STYLE = "background-color:#f0f000;";

    private const string OPTION_SEPERATOR_ROW_TEMPLATE = "<tr><td width=60 class=t_head style='height:20px;background-color: #ffffff; color:black;font-weight:bold;' >&nbsp; {0}</td><td width=400 class=t_head style='background-color: #ffffff; color:black;font-weight:bold;'>&nbsp;{1}</td><td width=80 class=t_head style='background-color: #ffffff; color:black;font-weight:bold;'>&nbsp;</td><td width=40 class=t_head colspan={2} style='background-color: #ffffff; color:black;font-weight:bold;'>&nbsp;</td></tr>";

    private static CultureInfo english = CultureInfo.GetCultureInfo("en-US");

    protected override string getReportFileName()
    {
        return "ANALIZ - " + base.getReportFileName();
    }

    private string prepareRowCover(string code, string text, double cumulative12Months, bool isEmpty, bool isOptionRow, bool isImportantRow)
    {
        return string.Format
        (
            "<tr>" +
                "<td width=40 class=vktxt8 {0} align=right>&nbsp;{1}{2}</td>" +
                "<td width=400 {3} class=vktxt8 >&nbsp;{4}{5}</td>" +
                "<td width=80 align=right class=vktxt8 {6} >{7}</td>"
            ,
            (isImportantRow ? ("style='" + IMPORTANT_CELL_STYLE + "'") : !isOptionRow ? "style='background-color: #DADADA;height:20px;'" : "")
            ,
            (isOptionRow ? "&nbsp;" : "")
            ,
            code
            ,
            (isImportantRow ? ("style='" + IMPORTANT_CELL_STYLE + "'") : !isOptionRow ? "style='background-color: #DADADA'" : "")
            ,
            (isOptionRow ? "&nbsp;&nbsp;" : "")
            ,
            text
            ,
            isImportantRow ? "style='" + IMPORTANT_CELL_STYLE + "'" : !isOptionRow ? "style='background-color: #DADADA'" : isEmpty ? "" : "bgcolor='#EAFFF9'"
            ,
            isEmpty ? "" : cumulative12Months.ToString("0.0")
        );
    }

    private static string getPresentationOfDateInterval(reportMonth month, int cumulativeMonths)
    {
        cumulativeMonths--;
        return
        (
            cumulativeMonths > 0
            ?
                (month - cumulativeMonths).getYear() != month.getYear()
                ?
                    (month - cumulativeMonths).getMonthName() + " " + (month - cumulativeMonths).getYear() + "-"
                :
                    (month - cumulativeMonths).getMonthName() + "-"
            :
                ""
        )
        +
        month.getMonthName() + " " + month.getYear();
    }

    private static string compareValuesGetTemplate(reportRowDefinition row, double value)
    {
        return compareValuesGetTemplate(row, value, 0);
    }
    private static string compareValuesGetTemplate(reportRowDefinition row, double value, int optionValue)
    {
        bool isImportantRow = optionValue > 0 ? row.getAttributeByName("io") == optionValue.ToString() : row.getAttributeByName("i") == "true";
        return isImportantRow ? (compareValues(row, value) ? SUCCESS_CELL_STYLE : FAILURE_CELL_STYLE) : "";
    }

    private static bool compareValues(reportRowDefinition row, double value)
    {
        double rootValue = getCompareValue(row);
        return row.getAttributeByName("op") == ">" ? value >= rootValue : value <= rootValue;
    }

    private static double getCompareValue(reportRowDefinition row)
    {
        return !string.IsNullOrEmpty(row.getAttributeByName("cv")) ? Convert.ToDouble(row.getAttributeByName("cv"), english) : 0;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureUserIsLoggedIn();

        excelReportName.Text = base.getReportFileName();
        excelExportDiv.Visible = !IsExcelDownloadRequest;

        reportDealerInfo reportInfoLast12Months = base.getCalculator().generateReportDataForSingleDealer(targetDealer, base.calculationType, base.endMonth - 11, base.endMonth);

        StringBuilder htmlBuilder = new StringBuilder();

        reportMonth[] monthsToColumns = reportMonth.getMonthsInInterval(base.startMonth, base.endMonth);

        tablewidth.Text = Convert.ToString(520 + monthsToColumns.Length * 80);

        SortedList<int, reportDealerInfo> reportDataCollection = new SortedList<int, reportDealerInfo>();

        foreach (reportMonth month in monthsToColumns)
        {
            htmlBuilder.AppendFormat(REPORT_HEADER_CELL_TEMPLATE, getPresentationOfDateInterval(month, base.cumulativeMonths));
            reportDataCollection.Add(month.dateValue, base.getCalculator().generateReportDataForSingleDealer(base.targetDealer, base.calculationType, month - (base.cumulativeMonths - 1), month));
        }

        reportHeader.Text = htmlBuilder.ToString();

        htmlBuilder = new StringBuilder();

        foreach (reportRowDefinition row in base.getDataCache().reportDefinitions["analysis"].rowDefinitions)
        {
            string rowType = row.getRowType();
            if (rowType.Equals("seperator_satisfaction"))
            {
                htmlBuilder.AppendFormat(REPORT_SEPERATOR_ROW_TEMPLATE, "A", "Memnuniyet", monthsToColumns.Length);
            }
            else if (rowType.Equals("seperator_quality"))
            {
                htmlBuilder.AppendFormat(REPORT_SEPERATOR_ROW_TEMPLATE, "A", "Hizmet Kalitesi", monthsToColumns.Length);
            }
            else if (rowType.Equals("seperator_overallevaluation"))
            {
                htmlBuilder.AppendFormat(REPORT_SEPERATOR_ROW_TEMPLATE, "BÖLÜM 1", "GENEL DEĞERLENDİRME", monthsToColumns.Length);
            }
            else if (rowType.Equals("seperator_fixedatthescene"))
            {
                htmlBuilder.AppendFormat(REPORT_SEPERATOR_ROW_TEMPLATE, "BÖLÜM 2", "OLAY YERİNDE ONARILANLAR", monthsToColumns.Length);
            }
            else if (rowType.Equals("seperator_fixedatthegarage"))
            {
                htmlBuilder.AppendFormat(REPORT_SEPERATOR_ROW_TEMPLATE, "BÖLÜM 3", "OLAY YERİNDE ONARILAMAYIP, SERVİSE ÇEKİLENLER", monthsToColumns.Length);
            }
            else if (rowType.Equals("seperator_servicequality"))
            {
                htmlBuilder.AppendFormat(REPORT_SEPERATOR_ROW_TEMPLATE, "BÖLÜM 4", "HİZMET KALİTESİ", monthsToColumns.Length);
            }
            else if (rowType.Equals("seperator_others"))
            {
                htmlBuilder.AppendFormat(REPORT_SEPERATOR_ROW_TEMPLATE, "BÖLÜM 5", "DİĞER", monthsToColumns.Length);
            }
            else if (rowType.Equals("percentage"))
            {
                questionDefinition questionToReport = base.getDataCache().questionDefinitions[row.getQuestionToReport()];

                htmlBuilder.AppendFormat(prepareRowCover(questionToReport.getCode(), questionToReport.getName(), 0, true, false, false));

                foreach (reportMonth month in monthsToColumns)
                {
                    htmlBuilder.Append(QUESTION_CELL);
                }

                foreach (optionDefinition opt in questionToReport.optionDefinitions.Values)
                {
                    if (opt.getAttributeByName("seperator") == "true")
                    {
                        htmlBuilder.AppendFormat(OPTION_SEPERATOR_ROW_TEMPLATE, opt.getValue(), opt.getText(), monthsToColumns.Length);
                        continue;
                    }
                    bool isImportantRow = row.getAttributeByName("io") == opt.getValue().ToString();
                    double cumulativeValue = reportInfoLast12Months.data.questions[questionToReport.getCode()].calculateOptionPercentage(opt.getValue()) * 100;

                    bool anyNonZero = cumulativeValue > 0d;

                    StringBuilder cellBuilder = new StringBuilder();
                    foreach (reportMonth month in monthsToColumns)
                    {
                        double value = reportDataCollection[month.dateValue].data.questions[questionToReport.getCode()].calculateOptionPercentage(opt.getValue()) * 100;
                        cellBuilder.AppendFormat(REPORT_CELL_DATA_TEMPLATE, value, compareValuesGetTemplate(row, value, opt.getValue()));
                        anyNonZero = anyNonZero || (value > 0d);
                    }
                    if (anyNonZero)
                    {
                        htmlBuilder.AppendFormat(prepareRowCover(opt.getValue().ToString(), opt.getText(), cumulativeValue, false, true, isImportantRow));
                        htmlBuilder.Append(cellBuilder);
                        htmlBuilder.Append("</tr>");
                    }
                }

            }
            else
            {
                questionDefinition questionToReport = base.getDataCache().questionDefinitions[row.getQuestionToReport()];
                StringBuilder cellBuilder = new StringBuilder();
                double yearlyCalculation = 0;
                bool isImportantRow = row.getAttributeByName("i") == "true";
                bool isYearlyCalculationDone = false;
                foreach (reportMonth month in monthsToColumns)
                {
                    double value = 0;
                    cumulativeData reportData = reportDataCollection[month.dateValue].data;
                    switch (rowType)
                    {
                        case Global.PROJECT_QVN:
                            value = reportData.questions[questionToReport.getCode()].calculateQvn() * 100;
                            cellBuilder.AppendFormat(REPORT_CELL_DATA_TEMPLATE, value, compareValuesGetTemplate(row, value));
                            if (!isYearlyCalculationDone)
                            {
                                yearlyCalculation = reportInfoLast12Months.data.questions[questionToReport.getCode()].calculateQvn() * 100;
                                isYearlyCalculationDone = true;
                            }
                            break;
                        case "formula_1":
                            value = reportData.questions[questionToReport.getCode()].calculateFormula1() * 100;
                            cellBuilder.AppendFormat(REPORT_CELL_DATA_TEMPLATE, value, compareValuesGetTemplate(row, value));
                            if (!isYearlyCalculationDone)
                            {
                                yearlyCalculation = reportInfoLast12Months.data.questions[questionToReport.getCode()].calculateFormula1() * 100;
                                isYearlyCalculationDone = true;
                            }
                            break;
                        case "formula_2":
                            value = reportData.questions[questionToReport.getCode()].calculateFormula2() * 100;
                            cellBuilder.AppendFormat(REPORT_CELL_DATA_TEMPLATE, value, compareValuesGetTemplate(row, value));
                            if (!isYearlyCalculationDone)
                            {
                                yearlyCalculation = reportInfoLast12Months.data.questions[questionToReport.getCode()].calculateFormula2() * 100;
                                isYearlyCalculationDone = true;
                            }
                            break;
                        case "percentage_over_total_base":
                            string[] optionsToReport = row.getAttributeByName("o").Split(',');
                            foreach (string optionToReportString in optionsToReport)
                            {
                                int optionToReport = Convert.ToInt32(optionToReportString);
                                value += reportData.questions[questionToReport.getCode()].getOptionCount(optionToReport);
                                if (!isYearlyCalculationDone)
                                {
                                    yearlyCalculation += reportInfoLast12Months.data.questions[questionToReport.getCode()].getOptionCount(optionToReport);
                                }
                            }
                            value = value * 100 / (double)reportData.baseCount;
                            cellBuilder.AppendFormat(REPORT_CELL_DATA_TEMPLATE, value, compareValuesGetTemplate(row, value));
                            if (!isYearlyCalculationDone)
                            {
                                yearlyCalculation = (yearlyCalculation * 100 / (double)reportInfoLast12Months.data.baseCount);
                                isYearlyCalculationDone = true;
                            }
                            break;
                        case "verbatim":
                            cellBuilder.AppendFormat(VERBATIM_CELL_DATA_TEMPLATE, month.dateValue, cumulativeMonths, base.getDealer().getCode(), questionToReport.getCode(), "Verbatim", row.getAttributeByName("varyby"));
                            break;

                    }
                }

                if (rowType != "verbatim")
                {
                    htmlBuilder.Append(prepareRowCover(rowType == "percentage_over_total_base" ? "" : questionToReport.getCode(), (rowType == "percentage_over_total_base" ? row.getAttributeByName("h") : questionToReport.getName()), yearlyCalculation, false, false, isImportantRow));
                }
                else
                {
                    htmlBuilder.Append(prepareRowCover(questionToReport.getCode(), questionToReport.getName(), 0, false, false, false));
                }
                htmlBuilder.Append(cellBuilder);
                htmlBuilder.Append("</tr>");
            }

        }

        reportHtml.Text = htmlBuilder.ToString();

        htmlBuilder = new StringBuilder();

        string dealerTypeCodes = "[dealer][branch][connected_point][satellite][network1][network2]";
        bool isDealer = dealerTypeCodes.Contains("[" + base.targetDealer.getTypeCode() + "]");
        bool isCoordinator = base.targetDealer.getTypeCode() == "coordinator";
        bool isArea = base.targetDealer.getTypeCode() == "area";

        string dealerRepresentation = base.targetDealer.getCode() + " - " + base.targetDealer.getName();

        htmlBuilder.AppendFormat(REPORT_SUMMARY_ROW_TEMPLATE, "Bayi", isDealer ? dealerRepresentation : "", "Görüşülen Kişi Sayısı", reportDataCollection[endMonth.dateValue].data.baseCount);
        htmlBuilder.AppendFormat(REPORT_SUMMARY_ROW_TEMPLATE, "Bölge", isArea ? dealerRepresentation : "", "Tarih aralığı", string.Format("{0} - {1:00} / {2} - {3:00}", startMonth.getYear(), startMonth.getMonth(), endMonth.getYear(), endMonth.getMonth()));
        htmlBuilder.AppendFormat(REPORT_SUMMARY_ROW_TEMPLATE, "Koordinatör", isCoordinator ? dealerRepresentation : "", "Şebeke Türü", base.getCalculatorTypeDescription());

        reportSummaryTableHtml.Text = htmlBuilder.ToString();

        base.RenderComplete();

        renderTime.Text = base.getElapsedRenderTime().ToString();

    }

}
